import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/check_in_info_state.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:dio/dio.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:permission_handler/permission_handler.dart";

/// 租客信息编辑组件
/// 用于编辑主要租客和同住人的基本信息、人脸认证等
class RenterInfo extends StatefulWidget {
  final RenterType renterType;  // 租客类型
  final Function changeInfo;    // 信息更新回调
  final Map info;              // 租客信息
  const RenterInfo({
    super.key, 
    required this.renterType, 
    required this.info, 
    required this.changeInfo,
  });

  @override
  State<StatefulWidget> createState() => _RenterInfoState();
}

/// 租客类型枚举
enum RenterType {
  renter,     // 主要租客
  cohabitant, // 同住人
}

class _RenterInfoState extends State<RenterInfo> {
  late ImagePicker _imagePicker;
  XFile? _imageFile;           // 临时存储选择的图片文件
  Map _info = {};             // 租客信息

  bool _verifySuccess = false; // 人脸验证是否成功
  bool _hasVerified = false;   // 是否已进行过人脸验证

  @override
  void didChangeDependencies() {
    setState(() {
      _info = widget.info;
      // 初始化验证状态 - verifyStatus: 0未认证，1认证成功
      _hasVerified = _info["verifyStatus"] != 0;
      _verifySuccess = _info["verifyStatus"] == 1;
    });
    super.didChangeDependencies();
  }

  /// 表单验证
  bool _validate() {
    if (Utils.isEmpty(_info["name"]) || Utils.isEmpty(_info["contacts"])) {
      EasyLoading.showToast("请填写完整信息");
      return false;
    }
    if (widget.renterType == RenterType.renter) {
      if (DateTime.parse(_info["checkInStart"]).isAfter(DateTime.parse(_info["checkInEnd"]))) {
        EasyLoading.showToast("结束时间要大于开始时间");
        return false;
      }
    }
    return true;
  }

  /// 渲染租客基本信息表单
  Widget _renderRenterInfo() {
    return MenuBlock(
        borderRadius: const BorderRadius.all(Radius.circular(0)),
        items: [
          MenuBlockItem(
            text: "姓名",
            showArrow: false,
            prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
              ),
              initialValue: _info["name"],
              onChanged: (value) {
                setState(() {
                  _info["name"] = value;
                });
              },
            ),
          ),
          MenuBlockItem(
            text: "联系方式",
            showArrow: false,
            prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
                counterText: "",
              ),
              maxLength: 11,
              initialValue: _info["contacts"],
              onChanged: (value) {
                setState(() {
                  _info["contacts"] = value;
                });
              },
            ),
          ),
          MenuBlockItem(
            text: "人脸",
            showArrow: false,
            tip: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FutureBuilder(
                  future: Future.delayed(const Duration(seconds: 1)),
                  builder: (context, snapshot) {
                    return _renderFace();
                  },
                ),
                const Text("人脸仅用于租客门禁开锁使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),)
              ],
            ),
            onTap: _showImageSourceOptions,
          ),
          MenuBlockItem(
            text: "证件号",
            showArrow: false,
            tip: const Text("证件号仅用于租客办理入住登记使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
                counterText: "",
              ),
              maxLength: 18,
              initialValue: _info["idCardNumber"],
              onChanged: (value) {
                setState(() {
                  _info["idCardNumber"] = value;
                });
              },
            ),
          )
        ]
    );
  }

  /// 渲染入住周期选择（仅主要租客）
  Widget _rentRange() {
    return Padding(
      padding: const EdgeInsets.only(top: 12),
      child: MenuBlock(
          title: const Text("入住周期"),
          borderRadius: const BorderRadius.all(Radius.circular(0)),
          items: [
            MenuBlockItem(
                text: "开始时间",
                prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
                suffix: Text(_info["checkInStart"]),
                onTap: () {
                  showDatetimePicker(
                      context: context,
                      initialDateTime: DateTime.parse(_info["checkInStart"]),
                      onchange: (value) => setState(() {
                        _info["checkInStart"] = DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
                      }),
                  );
                }
            ),
            MenuBlockItem(
                text: "结束时间",
                prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
                suffix: Text(_info["checkInEnd"]),
                onTap: () {
                  showDatetimePicker(
                    context: context,
                    initialDateTime: DateTime.parse(_info["checkInEnd"]),
                    onchange: (value) => setState(() {
                      _info["checkInEnd"] = DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
                    }),
                  );
                }
            ),
          ]
      ),
    );
  }

  /// 获取标题
  String _title() {
    switch (widget.renterType) {
      case RenterType.renter:
        return "入住人信息";
      case RenterType.cohabitant:
        return "编辑同住人";
    }
  }

  /// 渲染人脸图片上传区域
  /// 包含图片预览和验证状态提示
  Widget _renderFace() {
    Widget? imageWidget;
    
    // 判断是否有新上传的图片或已验证成功的图片
    if (_imageFile != null) {
      imageWidget = Image.file(
        File(_imageFile!.path),
        width: 150,
        height: 150,
        fit: BoxFit.cover,
      );
    } else if (_verifySuccess && _info["picUrl"] != null && _info["picUrl"].isNotEmpty) {
      imageWidget = Image.network(
        _info["picUrl"],
        width: 150,
        height: 150,
        fit: BoxFit.cover,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Center(
            child: CircularProgressIndicator(
              value: loadingProgress.expectedTotalBytes != null
                  ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                  : null,
            ),
          );
        },
        errorBuilder: (context, error, stackTrace) {
          return const Center(
            child: Icon(Icons.error, color: Colors.red, size: 40),
          );
        },
      );
    }

    String getStatusText() {
      if (!_hasVerified) return "请添加人脸认证";
      if (_verifySuccess) return "人脸身份校验成功";
      // 如果是新上传的图片验证失败，说明是上传失败
      if (_imageFile != null && _info["picUrl"] == null) return "上传失败，请重新上传";
      // 其他情况都是校验失败
      return "人脸身份校验失败";
    }

    return Container(
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        color: ThemeVars.colorBackground,
      ),
      child: Stack(
        children: [
          // 如果有图片则显示图片，否则显示添加图标
          Center(
            child: imageWidget ?? const Icon(Icons.add, size: 50),
          ),
          // 状态提示
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              height: 32,
              alignment: Alignment.center,
              color: Colors.white.withOpacity(0.7),
              child: Text(
                getStatusText(),
                style: TextStyle(
                  color: _hasVerified 
                    ? (_verifySuccess ? Colors.green : Colors.red)
                    : ThemeVars.colorTextSec,
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示选择图片来源的底部弹窗
  void _showImageSourceOptions() {
    // 使用变量跟踪当前是否有图片选择操作正在进行
    bool isPickerActive = false;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        title: const Text('选择图片来源'),
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              // 使用FutureBuilder的方式：先关闭弹窗，然后执行拍照
              Future.microtask(() {
                _takePhoto().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("拍照操作错误: $e");
                });
              });
            },
            child: const Text('拍照'),
          ),
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              // 使用FutureBuilder的方式：先关闭弹窗，然后执行选择图片
              Future.microtask(() {
                _pickImage().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("选择图片操作错误: $e");
                });
              });
            },
            child: const Text('从相册选择'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  /// 拍照获取图片
  Future<void> _takePhoto() async {
    try {
      var status = await Permission.camera.status;
      if (status.isDenied) {
        await Permission.camera.request();
      } else if (status.isGranted) {
        // 每次创建新的ImagePicker实例，避免状态冲突
        final picker = ImagePicker();
        final pickedImage = await picker.pickImage(
          source: ImageSource.camera,
          preferredCameraDevice: CameraDevice.front,
          imageQuality: 80,
        );

        if (pickedImage != null && mounted) {
          setState(() {
            _imageFile = pickedImage;
            _hasVerified = false;
          });
        }
      }

    } catch (e) {
      print("拍照错误: ${e.toString()}");
      EasyLoading.showError("拍照失败：${e.toString()}");
    }
  }

  /// 选择图片
  Future<void> _pickImage() async {
    try {
      // 每次创建新的ImagePicker实例，避免状态冲突
      final picker = ImagePicker();
      final pickedImage = await picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );
      
      if (pickedImage != null && mounted) {
        setState(() {
          _imageFile = pickedImage;
          _hasVerified = false;
        });
      }
    } catch (e) {
      print("拍照错误: ${e.toString()}");
      EasyLoading.showError("拍照失败：${e.toString()}");
    }
  }

  /// 更新入住信息
  Future<bool> _updateCheckIn() async {
    try {
      Map<String, dynamic> params = {
        "checkInId": _info["checkInId"],
        "checkInStart": _info["checkInStart"],
        "checkInEnd": _info["checkInEnd"],
      };
      await checkInApi.updateCheckIn(params);
      return true;
    } catch (e) {
      EasyLoading.showError("更新入住信息失败：${e.toString()}");
      return false;
    }
  }

  /// 更新租客信息
  Future<bool> _updateRenter() async {
    try {
      await checkInApi.updateRenter(_info);
      return true;
    } catch (e) {
      EasyLoading.showError("更新租客信息失败：${e.toString()}");
      return false;
    }
  }

  /// 删除同住人
  void _removeRenter(String id) async {
    await checkInApi.removeRenter(id);
    EasyLoading.showSuccess("删除成功");
    widget.changeInfo();
    if (context.mounted) {
      Navigator.pop(context);
    }
  }

  /// 上传图片到服务器
  Future<bool> _uploadImage() async {
    try {
      if (_imageFile == null) {
        throw Exception('No image selected');
      }

      final file = File(_imageFile!.path);
      
      // 检查文件大小是否超过5M
      final sizeInMB = Utils.getFileSizeInMB(file);
      if (sizeInMB > 5) {
        EasyLoading.showToast("请上传小于5M的图片");
        return false;
      }

      print('Starting image compression');
      File compressedFile;
      try {
        // 压缩图片至1M以下
        compressedFile = await Utils.compressImage(
          file,
          targetSizeInMB: 1.0,
          maxWidth: 1024,
          maxHeight: 1024,
        );
      } catch (e) {
        print('Compression error: $e');
        EasyLoading.showError("图片压缩失败，请选择其他图片");
        return false;
      }

      final finalSize = Utils.getFileSizeInMB(compressedFile);
      print('Final file size: ${finalSize.toStringAsFixed(2)}MB');

      FormData formData = FormData();
      formData.files.add(MapEntry(
        "file", 
        await MultipartFile.fromFile(
          compressedFile.path,
          filename: '${DateTime.now().millisecondsSinceEpoch}.jpg'
        )
      ));

      print('Uploading file');
      Map res = await commonApi.upload(formData);
      if (res["code"].toString() != "200") {
        EasyLoading.showError("人脸上传失败：${res["msg"] ?? "未知错误"}");
        setState(() {
          _hasVerified = true;
          _verifySuccess = false;
          _info["picUrl"] = null;
        });
        return false;
      }
      setState(() {
        _info["picUrl"] = res["data"]["url"];
      });
      return true;
    } catch (e, stackTrace) {
      print('Upload error: $e');
      print('Stack trace: $stackTrace');
      EasyLoading.showError("人脸上传失败：${e.toString()}");
      setState(() {
        _hasVerified = true;
        _verifySuccess = false;
        _info["picUrl"] = null;
      });
      return false;
    }
  }

  /// 进行人脸身份验证
  Future<bool> _verifyRenterInfo() async {
    // 验证必要信息是否完整
    if (Utils.isEmpty(_info["idCardNumber"]) || 
        Utils.isEmpty(_info["name"]) || 
        Utils.isEmpty(_info["picUrl"])) {
      EasyLoading.showError("请填写完整的身份信息和人脸照片");
      setState(() {
        _hasVerified = true;
        _verifySuccess = false;
      });
      return false;
    }

    Map<String, dynamic> params = {
      "idCardNumber": _info["idCardNumber"],
      "name": _info["name"],
      "picUrl": _info["picUrl"],
      "renterId": _info["renterId"],
    };

    try {
      await checkInApi.verifyInfo(_info["renterId"], params);
      setState(() {
        _hasVerified = true;
        _verifySuccess = true;
        _info["verifyStatus"] = 1;
      });
      return true;
    } catch(error) {
      EasyLoading.showError("人脸身份校验失败：${error.toString()}");
      setState(() {
        _hasVerified = true;
        _verifySuccess = false;
        _info["verifyStatus"] = 0;
      });
      return false;
    }
  }

  /// 处理保存操作
  void _handleSave() async {
    EasyLoading.show();
    if (!_validate()) return;

    // 1. 上传新图片（如果有）
    if (_imageFile != null) {
      bool uploadSuccess = await _uploadImage();
      if (!uploadSuccess) return;
    }
    
    // 2. 进行人脸核身校验
    bool verifySuccess = await _verifyRenterInfo();
    if (!verifySuccess) return;

    // 3. 更新入住信息（主要租客）
    if (widget.renterType == RenterType.renter) {
      bool checkInSuccess = await _updateCheckIn();
      if (!checkInSuccess) return;
    }

    // 4. 更新租客信息
    bool renterSuccess = await _updateRenter();
    if (!renterSuccess) return;

    // 所有操作成功后
    EasyLoading.showSuccess("保存成功");
    widget.changeInfo();
    Stacker.pop();
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    setState(() {
      _info = widget.info;
      _hasVerified = _info["verifyStatus"] != 0;
      _verifySuccess = _info["verifyStatus"] == 1;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: _title(),
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      child: ListView(
        children: [
          _renderRenterInfo(),
          if (widget.renterType == RenterType.renter) _rentRange(),
          Padding(
            padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 40, ThemeVars.paddingPage, 0),
            child: Button(
              type: ButtonType.primary,
              onPressed: _handleSave,
              child: const Text("保存"),
            ),
          ),
          widget.renterType == RenterType.cohabitant ?  Padding(
            padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 12, ThemeVars.paddingPage, 30),
            child: Button(
              type: ButtonType.dangerOutline,
              onPressed: () {
                taiDialog(
                  context: context,
                  child: const Text("确定删除同住人？", textAlign: TextAlign.center,),
                  onConfirm: (ctx) {
                    Navigator.of(ctx).pop();
                    _removeRenter(_info["renterId"].toString());
                  }
                );
              },
              child: const Text("删除同住人"),
            ),
          ) : const SizedBox(height: 30,),
        ],
      ),
    );
  }
}